import re
import nltk
import logging
import re
import pycrfsuite
from nltk.corpus import cmudict
from typing import List, Dict, Tuple, Optional, Any

# 配置日志
logger = logging.getLogger(__name__)

class PhoneticConverter:
    def __init__(self):
        """初始化拼读转换器，加载NLTK和CMU词典以及CRFSuite相关功能"""
        try:
            # 下载必要的NLTK资源（如果尚未下载）
            nltk.download('punkt')
            nltk.download('averaged_perceptron_tagger')
            nltk.download('cmudict')
            
            # 加载CMU发音词典
            self.pronunciation_dict = cmudict.dict()
            
            # 补充例外词词典（常见但CMU词典中可能缺失的词）
            self.exception_words = {
                'okay': ['O', 'K', 'A', 'Y'],
                'OK': ['O', 'K'],
                'bye': ['B', 'Y', 'E'],
                'hi': ['H', 'I'],
                'hello': ['H', 'E', 'L', 'L', 'O'],
                'hey': ['H', 'E', 'Y'],
                'nope': ['N', 'O', 'P', 'E'],
                'yep': ['Y', 'E', 'P'],
                'hmm': ['H', 'M', 'M'],
                'uh-oh': ['U', 'H', '-', 'O', 'H'],
                'etc': ['E', 'T', 'C'],
                'vs': ['V', 'S'],
                'i.e': ['I', '.', 'E'],
                'e.g': ['E', '.', 'G'],
                'www': ['W', 'W', 'W'],
                'email': ['E', 'M', 'A', 'I', 'L'],
                'phone': ['P', 'H', 'O', 'N', 'E'],
                'SMS': ['S', 'M', 'S'],
                'app': ['A', 'P', 'P'],
                'WiFi': ['W', 'I', 'F', 'I'],
                'USB': ['U', 'S', 'B'],
                'PDF': ['P', 'D', 'F'],
                'CD': ['C', 'D'],
                'DVD': ['D', 'V', 'D'],
                'TV': ['T', 'V'],
                'GPS': ['G', 'P', 'S'],
                'LED': ['L', 'E', 'D'],
                'USA': ['U', 'S', 'A'],
                'UK': ['U', 'K'],
                'UN': ['U', 'N'],
                'NASA': ['N', 'A', 'S', 'A'],
                'FBI': ['F', 'B', 'I'],
                'CIA': ['C', 'I', 'A'],
                'CEO': ['C', 'E', 'O'],
                'VIP': ['V', 'I', 'P'],
                'ATM': ['A', 'T', 'M'],
                'COVID': ['C', 'O', 'V', 'I', 'D'],
                'AI': ['A', 'I'],
                'ML': ['M', 'L'],
                'IoT': ['I', 'O', 'T'],
                'URL': ['U', 'R', 'L'],
                'HTTP': ['H', 'T', 'T', 'P'],
                'HTTPS': ['H', 'T', 'T', 'P', 'S'],
                'API': ['A', 'P', 'I'],
                'SDK': ['S', 'D', 'K'],
                'IDE': ['I', 'D', 'E'],
                'JSON': ['J', 'S', 'O', 'N'],
                'XML': ['X', 'M', 'L'],
                'SQL': ['S', 'Q', 'L'],
                'CPU': ['C', 'P', 'U'],
                'GPU': ['G', 'P', 'U'],
                'RAM': ['R', 'A', 'M'],
                'ROM': ['R', 'O', 'M'],
                'SSD': ['S', 'S', 'D'],
                'HDD': ['H', 'D', 'D'],
                'QR': ['Q', 'R'],
                'NFC': ['N', 'F', 'C'],
                'HDMI': ['H', 'D', 'M', 'I'],
                'USB-C': ['U', 'S', 'B', '-', 'C'],
                '4K': ['4', 'K'],
                '8K': ['8', 'K'],
                '5G': ['5', 'G'],
                '4G': ['4', 'G'],
                '3G': ['3', 'G'],
                'LOL': ['L', 'O', 'L'],
                'OMG': ['O', 'M', 'G'],
                'IMHO': ['I', 'M', 'H', 'O'],
                'TBH': ['T', 'B', 'H'],
                'BRB': ['B', 'R', 'B'],
                'TTYL': ['T', 'T', 'Y', 'L'],
                'AFK': ['A', 'F', 'K'],
                'GTG': ['G', 'T', 'G'],
                'IDK': ['I', 'D', 'K'],
                'BTW': ['B', 'T', 'W'],
                'FYI': ['F', 'Y', 'I'],
                'ASAP': ['A', 'S', 'A', 'P'],
                'ETC': ['E', 'T', 'C'],
                'DIY': ['D', 'I', 'Y'],
                'YOLO': ['Y', 'O', 'L', 'O'],
                'FOMO': ['F', 'O', 'M', 'O'],
                'TBD': ['T', 'B', 'D'],
                'ETA': ['E', 'T', 'A'],
                'FAQ': ['F', 'A', 'Q'],
                'VIP': ['V', 'I', 'P'],
                'MVP': ['M', 'V', 'P'],
                'ROI': ['R', 'O', 'I'],
                'KPI': ['K', 'P', 'I'],
                'SWOT': ['S', 'W', 'O', 'T'],
                'PEST': ['P', 'E', 'S', 'T'],
                'SMART': ['S', 'M', 'A', 'R', 'T'],
                'SWOT': ['S', 'W', 'O', 'T'],
                'PEST': ['P', 'E', 'S', 'T'],
                'SMART': ['S', 'M', 'A', 'R', 'T'],
            }
            
            # 初始化CRFSuite标记器
            self.crf_tagger = pycrfsuite.Tagger()
            
            # 由于是演示，我们使用一个简单的基于规则的CRFSuite实现
            # 在实际应用中，这里应该加载一个训练好的CRF模型
            logger.info("PhoneticConverter初始化成功，已加载NLTK资源、CMU词典和CRFSuite功能")
        except Exception as e:
            logger.error(f"PhoneticConverter初始化失败: {e}")
            raise
    
    def text_to_phonetics(self, text: str) -> Dict[str, List[str]]:
        """将文本转换为音素表示
        
        Args:
            text: 输入文本
            
        Returns:
            字典，包含原始文本、音素表示和分词结果
        """
        try:
            # 预处理文本
            text = text.strip()
            if not text:
                return {
                    "original_text": text,
                    "phonetic_representation": [],
                    "tokens": []
                }
            
            # 分词和词性标注
            tokens = nltk.word_tokenize(text)
            tagged_tokens = nltk.pos_tag(tokens)
            
            # 转换为音素表示
            phonetic_result = []
            for word, pos in tagged_tokens:
                # 检查是否为特殊词或首字母缩略词
                if word.upper() in self.exception_words:
                    phonetic_result.extend(self.exception_words[word.upper()])
                # 检查是否为数字
                elif word.isdigit():
                    phonetic_result.extend(self._number_to_phonetics(word))
                # 检查是否为标点符号
                elif not re.match(r'[a-zA-Z0-9]', word):
                    # 对于标点符号，直接添加
                    phonetic_result.append(word)
                # 检查是否在CMU词典中
                elif word.lower() in self.pronunciation_dict:
                    # 从CMU词典获取发音（选择第一个发音）
                    pronunciation = self.pronunciation_dict[word.lower()][0]
                    # 移除重音标记并转换为大写
                    cleaned_pronunciation = [re.sub(r'\d', '', phone).upper() for phone in pronunciation]
                    phonetic_result.extend(cleaned_pronunciation)
                else:
                    # 对于词典中没有的词，按字母拼读
                    phonetic_result.extend([char.upper() for char in word if char.isalnum()])
                
            return {
                "original_text": text,
                "phonetic_representation": phonetic_result,
                "tokens": tagged_tokens
            }
        except Exception as e:
            logger.error(f"文本转音素过程中发生错误: {e}")
            raise
    
    def _number_to_phonetics(self, number: str) -> List[str]:
        """将数字转换为音素表示
        
        Args:
            number: 数字字符串
            
        Returns:
            数字的音素表示列表
        """
        # 数字的英文发音映射
        digit_pronunciations = {
            '0': ['Z', 'E', 'R', 'O'],
            '1': ['O', 'N', 'E'],
            '2': ['T', 'W', 'O'],
            '3': ['T', 'H', 'R', 'E', 'E'],
            '4': ['F', 'O', 'U', 'R'],
            '5': ['F', 'I', 'V', 'E'],
            '6': ['S', 'I', 'X'],
            '7': ['S', 'E', 'V', 'E', 'N'],
            '8': ['E', 'I', 'G', 'H', 'T'],
            '9': ['N', 'I', 'N', 'E']
        }
        
        result = []
        for digit in number:
            if digit in digit_pronunciations:
                result.extend(digit_pronunciations[digit])
            else:
                # 对于特殊数字字符（如小数点），直接添加
                result.append(digit)
        
        return result
        
    def phonetics_to_spelling_text(self, phonetic_representation: List[str]) -> str:
        """将音素表示转换为可读的拼写文本（用于拼读语音生成）
        
        Args:
            phonetic_representation: 音素表示列表
        
        Returns:
            可读的拼写文本字符串
        """
        try:
            # 过滤掉标点符号和空字符串
            filtered_phonetics = [p for p in phonetic_representation if p.isalnum() or p == '-']
            
            # 记录字母并打印出来
            letters = [p for p in filtered_phonetics if p.isalpha()]
            if letters:
                logger.info(f"拼写的字母列表: {letters}")
                print(f"[拼读信息] 单词包含的字母: {letters}")
            
            # 将音素列表转换为空格连接的字符串
            # 例如: ['H', 'E', 'L', 'L', 'O'] -> 'H E L L O'
            return ' '.join(filtered_phonetics)
        except Exception as e:
            logger.error(f"音素转拼写文本过程中发生错误: {e}")
            raise

    def word_to_spelling(self, word: str, mode: str = "letter_by_letter", 
                         with_pronunciation: bool = False, 
                         letter_separator: str = " ",
                         with_word_pronunciation: bool = False) -> Dict[str, str]:
        """高级单词拼读方法，支持多种拼读模式
        
        Args:
            word: 要拼读的单词
            mode: 拼读模式，可选值:
                - "letter_by_letter": 字母逐一拼读（默认）
                - "letter_name": 按字母名称拼读
                - "phonemic": 按音素拼读
                - "combination": 字母组合拼读
            with_pronunciation: 是否在每个字母后添加发音说明
            letter_separator: 字母之间的分隔符
            with_word_pronunciation: 是否在拼读前添加整个单词的发音
            
        Returns:
            字典，包含原始单词、拼读文本和拼读信息
        """
        try:
            # 记录单词
            logger.info(f"正在处理单词拼读: {word}")
            print(f"[拼读信息] 处理单词: {word}")
            
            # 预处理单词
            word = word.strip()
            if not word:
                return {
                    "word": word,
                    "spelling_text": "",
                    "info": "Empty word"
                }
            
            result = {
                "word": word,
                "spelling_text": "",
                "info": f"Mode: {mode}, Separator: '{letter_separator}'"
            }
            
            # 验证模式参数
            valid_modes = ['letter_by_letter', 'letter_name', 'phonemic', 'combination', 'crfsuite']
            if mode not in valid_modes:
                raise ValueError(f"无效的模式参数: {mode}。有效模式: {', '.join(valid_modes)}")
            
            # 打印当前使用的拼读模式
            logger.info(f"当前使用的拼读模式: {mode}")
            print(f"[拼读信息] 当前使用的拼读模式: {mode}")
            
            # 根据不同模式生成拼读文本
            if mode == "letter_by_letter":
                # 简单的字母逐一拼读
                letters = [char for char in word if char.isalnum()]
                result["spelling_text"] = letter_separator.join(letters)
                
                # 记录字母
                logger.info(f"字母列表: {letters}")
                print(f"[拼读信息] 单词包含的字母: {letters}")
                
            elif mode == "letter_name":
                # 按字母名称拼读（如A读作"ei"，B读作"bi"等）
                letter_names = {
                    'A': 'ei', 'B': 'bi', 'C': 'si', 'D': 'di', 'E': 'i',
                    'F': 'ef', 'G': 'dʒi', 'H': 'eitʃ', 'I': 'ai', 'J': 'dʒei',
                    'K': 'kei', 'L': 'el', 'M': 'em', 'N': 'en', 'O': 'əu',
                    'P': 'pi', 'Q': 'kju', 'R': 'ɑr', 'S': 'es', 'T': 'ti',
                    'U': 'ju', 'V': 'vi', 'W': 'dʌblju', 'X': 'eks', 'Y': 'wai',
                    'Z': 'zi' if word.isupper() else 'zed'
                }
                
                spelling_parts = []
                letters = []
                
                for char in word:
                    if char.isalpha():
                        upper_char = char.upper()
                        letters.append(upper_char)
                        
                        if upper_char in letter_names:
                            spelling_parts.append(letter_names[upper_char])
                        else:
                            spelling_parts.append(upper_char)
                    elif char.isdigit():
                        spelling_parts.append(self._number_to_words(char))
                        letters.append(char)
                    else:
                        spelling_parts.append(char)
                
                result["spelling_text"] = letter_separator.join(spelling_parts)
                result["info"] += f", Letter names used"
                
                # 记录字母
                logger.info(f"字母列表: {letters}")
                print(f"[拼读信息] 单词包含的字母: {letters}")
                
            elif mode == "phonemic":
                # 按音素拼读（使用CMU词典）
                if word.lower() in self.pronunciation_dict:
                    pronunciation = self.pronunciation_dict[word.lower()][0]
                    cleaned_pronunciation = [re.sub(r'\d', '', phone).upper() for phone in pronunciation]
                    result["spelling_text"] = letter_separator.join(cleaned_pronunciation)
                    result["info"] += f", Phonemic transcription from CMU dict"
                else:
                    # 如果词典中没有，回退到字母拼读
                    letters = [char.upper() for char in word if char.isalnum()]
                    result["spelling_text"] = letter_separator.join(letters)
                    result["info"] += f", Fallback to letter by letter (not in CMU dict)"
                
            elif mode == "combination":
                # 字母组合拼读（识别常见的字母组合）
                # 常见的字母组合
                combinations = {
                    'TH': 'θ', 'SH': 'ʃ', 'CH': 'tʃ', 'PH': 'f',
                    'GH': 'g', 'WH': 'w', 'QU': 'kw', 'CK': 'k',
                    'NG': 'ŋ', 'NK': 'ŋk', 'DGE': 'dʒ', 'TCH': 'tʃ',
                    'AI': 'ei', 'AY': 'ei', 'EA': 'i', 'EE': 'i',
                    'IE': 'i', 'OA': 'əu', 'OW': 'əu', 'OY': 'ɔi',
                    'AU': 'ɔ', 'AW': 'ɔ', 'OU': 'au', 'OO': 'u',
                    'OI': 'ɔi', 'EY': 'ei', 'AYE': 'ei', 'ERE': 'iə',
                    'IRE': 'aiə', 'URE': 'juə', 'EAR': 'iə', 'AIR': 'eə',
                    'OUR': 'auə', 'OR': 'ɔr', 'ER': 'ər', 'AR': 'ɑr',
                    'UR': 'ər', 'WR': 'r', 'KN': 'n', 'GN': 'n'
                }
                
                i = 0
                word_upper = word.upper()
                spelling_parts = []
                letters = []
                
                while i < len(word_upper):
                    # 尝试匹配最长的可能组合
                    matched = False
                    for length in range(3, 0, -1):
                        if i + length <= len(word_upper):
                            combo = word_upper[i:i+length]
                            if combo in combinations and combo.isalpha():
                                spelling_parts.append(combo)
                                letters.extend(list(combo))
                                i += length
                                matched = True
                                break
                    
                    # 如果没有匹配到组合，添加单个字符
                    if not matched:
                        char = word_upper[i]
                        if char.isalnum():
                            spelling_parts.append(char)
                            if char.isalpha():
                                letters.append(char)
                        i += 1
                
                result["spelling_text"] = letter_separator.join(spelling_parts)
                result["info"] += f", Letter combinations recognition"
                
                # 记录字母
                logger.info(f"字母列表: {letters}")
                print(f"[拼读信息] 单词包含的字母: {letters}")
                
            elif mode == "crfsuite":
                # CRFSuite + CMU词典拼读模式
                # 提取单词特征用于CRFSuite
                features = self._extract_word_features(word)
                
                try:
                    # 尝试使用CRFSuite进行序列标记
                    # 由于是演示，我们使用简单的规则来模拟CRFSuite的输出
                    # 在实际应用中，这里应该加载训练好的模型并进行预测
                    best_sequence = self._simulate_crf_prediction(features, word)
                    
                    # 根据CRFSuite预测的序列生成拼读文本
                    result["spelling_text"] = letter_separator.join(best_sequence)
                    result["info"] += f", CRFSuite-based pronunciation"
                    
                    if with_word_pronunciation:
                        # 获取单词发音
                        phonetics = self.text_to_phonetics(word)
                        pronunciation_text = " " + self.phonetics_to_spelling_text(phonetics["phonetic_representation"])
                        result["spelling_text"] += pronunciation_text
                except Exception as e:
                    logger.warning(f"CRFSuite拼读模式失败，回退到混合模式: {e}")
                    # 如果CRFSuite失败，回退到混合模式
                    # 常见的字母组合
                    combinations = {
                        'TH': 'θ', 'SH': 'ʃ', 'CH': 'tʃ', 'PH': 'f',
                        'GH': 'g', 'WH': 'w', 'QU': 'kw', 'CK': 'k',
                        'NG': 'ŋ', 'NK': 'ŋk', 'DGE': 'dʒ', 'TCH': 'tʃ',
                        'AI': 'ei', 'AY': 'ei', 'EA': 'i', 'EE': 'i',
                        'IE': 'i', 'OA': 'əu', 'OW': 'əu', 'OY': 'ɔi',
                        'AU': 'ɔ', 'AW': 'ɔ', 'OU': 'au', 'OO': 'u',
                        'OI': 'ɔi', 'EY': 'ei', 'AYE': 'ei', 'ERE': 'iə',
                        'IRE': 'aiə', 'URE': 'juə', 'EAR': 'iə', 'AIR': 'eə',
                        'OUR': 'auə', 'OR': 'ɔr', 'ER': 'ər', 'AR': 'ɑr',
                        'UR': 'ər', 'WR': 'r', 'KN': 'n', 'GN': 'n'
                    }
                    
                    i = 0
                    word_upper = word.upper()
                    spelling_parts = []
                    letters = []
                    
                    while i < len(word_upper):
                        # 尝试匹配最长的可能组合
                        matched = False
                        for length in range(3, 0, -1):
                            if i + length <= len(word_upper):
                                combo = word_upper[i:i+length]
                                if combo in combinations and combo.isalpha():
                                    spelling_parts.append(combo)
                                    letters.extend(list(combo))
                                    i += length
                                    matched = True
                                    break
                        
                        # 如果没有匹配到组合，添加单个字符
                        if not matched:
                            char = word_upper[i]
                            if char.isalnum():
                                spelling_parts.append(char)
                                if char.isalpha():
                                    letters.append(char)
                            i += 1
                    
                    result["spelling_text"] = letter_separator.join(spelling_parts)
                    result["info"] += f", Fallback to letter combinations recognition"
                    
                    if with_word_pronunciation:
                        # 获取单词发音
                        phonetics = self.text_to_phonetics(word)
                        pronunciation_text = " " + self.phonetics_to_spelling_text(phonetics["phonetic_representation"])
                        result["spelling_text"] += pronunciation_text
            
            # 添加单词发音（如果需要）
            if with_word_pronunciation:
                phonetic_result = self.text_to_phonetics(word)
                pronunciation_text = ' '.join(phonetic_result["phonetic_representation"])
                result["spelling_text"] = f"{word} {pronunciation_text} {result['spelling_text']}"
                result["info"] += ", With word pronunciation"
            
            # 添加字母发音说明（如果需要）
            if with_pronunciation and mode == "letter_by_letter":
                letter_pronunciations = {}
                # 这里可以添加更多字母的发音说明
                result["info"] += ", With letter pronunciations"
                # 注意：实际实现可能需要更复杂的逻辑来添加发音说明
            
            logger.info(f"单词拼读完成: {word} -> {result['spelling_text']}")
            print(f"[拼读信息] 拼读结果: {result['spelling_text']}")
            
            return result
        except Exception as e:
            logger.error(f"单词拼读过程中发生错误: {e}")
            raise
    
    def _extract_word_features(self, word: str) -> List[Dict[str, Any]]:
        """为单词提取用于CRFSuite的特征"""
        features = []
        word_lower = word.lower()
        word_upper = word.upper()
        
        for i in range(len(word)):
            feature = {
                'current_char': word_lower[i],
                'current_char_upper': word_upper[i],
                'is_first': i == 0,
                'is_last': i == len(word) - 1,
                'is_alpha': word[i].isalpha(),
                'is_digit': word[i].isdigit(),
                'is_vowel': word_lower[i] in 'aeiouy',
                'is_consonant': word_lower[i].isalpha() and word_lower[i] not in 'aeiouy'
            }
            
            # 前后字符特征
            if i > 0:
                feature['prev_char'] = word_lower[i-1]
                feature['prev_char_upper'] = word_upper[i-1]
                feature['prev_is_vowel'] = word_lower[i-1] in 'aeiouy'
            else:
                feature['BOS'] = True  # 句首标记
            
            if i < len(word) - 1:
                feature['next_char'] = word_lower[i+1]
                feature['next_char_upper'] = word_upper[i+1]
                feature['next_is_vowel'] = word_lower[i+1] in 'aeiouy'
            else:
                feature['EOS'] = True  # 句尾标记
            
            # 字母组合特征
            if i > 0 and i < len(word) - 1:
                feature['tri_char'] = word_lower[i-1:i+2]
                feature['tri_char_upper'] = word_upper[i-1:i+2]
            
            if i < len(word) - 1:
                feature['bi_char'] = word_lower[i:i+2]
                feature['bi_char_upper'] = word_upper[i:i+2]
            
            # 单词位置特征
            feature['position'] = i / (len(word) - 1) if len(word) > 1 else 0
            
            features.append(feature)
        
        return features
        
    def _simulate_crf_prediction(self, features: List[Dict[str, Any]], word: str) -> List[str]:
        """模拟CRFSuite的预测结果
        
        在实际应用中，这里应该使用训练好的CRF模型进行预测
        这里使用基于规则的方法来模拟CRFSuite的输出，使拼读更加自然
        """
        word_upper = word.upper()
        result = []
        i = 0
        
        # 常见的字母组合及其发音表示
        common_combinations = {
            'TH': 'TH', 'SH': 'SH', 'CH': 'CH', 'PH': 'PH',
            'GH': 'GH', 'WH': 'WH', 'QU': 'QU', 'CK': 'CK',
            'NG': 'NG', 'NK': 'NK', 'DGE': 'DGE', 'TCH': 'TCH',
            'AI': 'AI', 'AY': 'AY', 'EA': 'EA', 'EE': 'EE',
            'IE': 'IE', 'OA': 'OA', 'OW': 'OW', 'OY': 'OY',
            'AU': 'AU', 'AW': 'AW', 'OU': 'OU', 'OO': 'OO',
            'OI': 'OI', 'EY': 'EY', 'AYE': 'AYE', 'ERE': 'ERE',
            'IRE': 'IRE', 'URE': 'URE', 'EAR': 'EAR', 'AIR': 'AIR',
            'OUR': 'OUR', 'OR': 'OR', 'ER': 'ER', 'AR': 'AR',
            'UR': 'UR', 'WR': 'WR', 'KN': 'KN', 'GN': 'GN'
        }
        
        while i < len(word_upper):
            # 尝试匹配最长的可能组合
            matched = False
            
            # 检查3字母组合
            if i + 3 <= len(word_upper):
                combo = word_upper[i:i+3]
                if combo in common_combinations:
                    result.append(combo)
                    i += 3
                    matched = True
            
            # 检查2字母组合
            if not matched and i + 2 <= len(word_upper):
                combo = word_upper[i:i+2]
                if combo in common_combinations:
                    result.append(combo)
                    i += 2
                    matched = True
            
            # 检查CMU词典中的发音
            if not matched and i < len(word_upper):
                # 尝试从当前位置开始的最长子串是否在CMU词典中
                for j in range(min(len(word_upper), i + 6), i, -1):
                    sub_word = word_upper[i:j].lower()
                    if sub_word in self.pronunciation_dict:
                        result.append(word_upper[i:j])
                        i = j
                        matched = True
                        break
            
            # 如果没有匹配到任何组合，添加单个字符
            if not matched:
                result.append(word_upper[i])
                i += 1
        
        return result
        
    def _number_to_words(self, digit: str) -> str:
        """将单个数字转换为英文单词
        
        Args:
            digit: 单个数字字符
            
        Returns:
            数字的英文单词
        """
        digit_words = {
            '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
            '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'
        }
        
        return digit_words.get(digit, digit)

# 单例实例
phonetic_converter = PhoneticConverter()

# 导出函数
def text_to_phonetics(text: str) -> Dict[str, List[str]]:
    """将文本转换为音素表示（便捷函数）
    
    Args:
        text: 输入文本
        
    Returns:
        字典，包含原始文本、音素表示和分词结果
    """
    return phonetic_converter.text_to_phonetics(text)

def phonetics_to_spelling_text(phonetic_representation: List[str]) -> str:
    """将音素表示转换为可读的拼写文本（便捷函数）
    
    Args:
        phonetic_representation: 音素表示列表
        
    Returns:
        可读的拼写文本字符串
    """
    return phonetic_converter.phonetics_to_spelling_text(phonetic_representation)

def word_to_spelling(word: str, mode: str = "letter_by_letter", 
                     with_pronunciation: bool = False, 
                     letter_separator: str = " ",
                     with_word_pronunciation: bool = False) -> Dict[str, str]:
    """高级单词拼读方法（便捷函数）
    
    Args:
        word: 要拼读的单词
        mode: 拼读模式，可选值:
            - "letter_by_letter": 字母逐一拼读（默认）
            - "letter_name": 按字母名称拼读
            - "phonemic": 按音素拼读
            - "combination": 字母组合拼读
            - "crfsuite": CRFSuite+CMU词典拼读
        with_pronunciation: 是否在每个字母后添加发音说明
        letter_separator: 字母之间的分隔符
        with_word_pronunciation: 是否在拼读前添加整个单词的发音
        
    Returns:
        字典，包含原始单词、拼读文本和拼读信息
    """
    return phonetic_converter.word_to_spelling(word, mode, with_pronunciation, 
                                             letter_separator, with_word_pronunciation)